<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />

      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click.native="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { newDepartment, getDepartmentDetails, putDepartment } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 判断name 是否重复
    const validName = (rule, value, callback) => {
      // 思路：被占用的名字是这个部门的子部门
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // 如果是编辑状态
      if (this.isEdit) {
        // 只能获取到当前编辑的部门的id，获取到当前编辑部门的pid
        const pid = this.originList.find(item => item.id === this.id).pid
        existNameList = this.originList.filter(item => item.pid === pid).filter(item => item.id !== this.id).map(item => item.name)
      }
      console.log('被占用的名字列表', existNameList)

      if (existNameList.includes(value)) {
        callback(new Error(`这个${value}已经被占用`))
      } else {
        callback()
      }
    }
    // 判断code 是否重复
    const validCode = (rule, value, callback) => {
      let codeList = this.originList.map(item => item.code)
      // console.log('codeList', codeList) // 打印的是所有code
      // 如果是编辑状态下  传过来的id 不等于当前元素的id
      // 就把他的code 拿出来
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
        console.log('现在是编辑状态,正在编辑的id是', this.id)
      }
      if (codeList.includes(value)) {
        callback(new Error(`已经存在当前编码${value},请重新输入`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      list: [], // 保存部门负责人
      // 自定义验证规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 15, message: '部门名称要求1-15个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 15, message: '部门编码要求1-15个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadEmployeeSimple()
    // 如果时编辑状态才让获取详细信息
    if (this.isEdit) {
      this.loadDepartmentDetails()
    }
  },
  methods: {
    // 获取部门详细数据
    async  loadDepartmentDetails() {
      const res = await getDepartmentDetails(this.id)
      console.log(res)
      this.form = res.data
    },
    // 编辑部门
    async doEdit() {
      try {
        const res = await putDepartment(this.form)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 成功之后 渲染数据 关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 新增部门
    async doAdd() {
      try {
        const res = await newDepartment({ pid: this.id, ...this.form })
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取部门负责人
    async  loadEmployeeSimple() {
      try {
        const res = await getEmployeeSimple()
        console.log('部门负责人', res)
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 确定
    hSubmit() {
      // 兜底检验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 检验失败
        // 成功才能执行下面代码
        // isedit 为true 就是编辑  为false 就是新增
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>
